package com.cqq.base.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.cqq.auth.service.PermResourceService;
import com.cqq.auth.service.bean.MenuBean;
import com.cqq.auth.service.bean.UserBean;
import com.cqq.common.core.constant.SessionConstant;
import com.cqq.common.core.util.ListBuilder;

/**
 * <h3>会话过滤器</h3>
 * 
 * @author GUOQIANG
 * @version 1.0.0
 */
@Component("sessionFilter")
public class SessionFilter extends OncePerRequestFilter {

	@Value("${system.code}")
	private String systemCode;

	@Autowired
	private PermResourceService permResourceService;

	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		FMContext.getCurrent().setSystemCode(systemCode);

		HttpSession session = request.getSession(true);
		UserBean user = FMContext.getLoginUser();

		if (user != null) {
			FMContext.getCurrent().setUserId(user.getId());

			processMenu(request, session);
		}else{
			String type = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equalsIgnoreCase(type)) {// AJAX REQUEST PROCESS
                response.setHeader("sessionstatus", "timeout");
            }
		}

		filterChain.doFilter(request, response);
	}

	

	@SuppressWarnings("unchecked")
	private void processMenu(HttpServletRequest request, HttpSession session) {
		//menus
		List<MenuBean> menus = (List<MenuBean>) session.getAttribute(SessionConstant.MENUS);
		if (CollectionUtils.isEmpty(menus)) {
			menus = permResourceService.listMenu(FMContext.getCurrent().getUserId(), systemCode);
			if (menus == null) {
				menus = ListBuilder.newArrayList();
			}
			session.setAttribute(SessionConstant.MENUS, menus);
		}

		//current menu
		MenuBean selectedMenu = getSelectedMenu(request.getRequestURI(), menus);
		if (selectedMenu != null) {
			session.setAttribute(SessionConstant.MENU_SELECTED, selectedMenu);
		}
	}

	private MenuBean getSelectedMenu(String uri, List<MenuBean> menus) {
		for (MenuBean menu : menus) {
			if (StringUtils.isNoneBlank(menu.getUrl()) && uri.contains(menu.getUrl())) {
				MenuBean selectedMenu = new MenuBean();
				selectedMenu.setId(menu.getId());
				selectedMenu.setUrl(menu.getUrl());
				return selectedMenu;
			}
			if (CollectionUtils.isNotEmpty(menu.getChildren())) {

				MenuBean selectedMenu = getSelectedMenu(uri, menu.getChildren());//迭代

				if (selectedMenu != null) {
					MenuBean selectedParentMenu = new MenuBean();
					selectedParentMenu.setId(menu.getId());
					selectedParentMenu.setUrl(menu.getUrl());
					List<MenuBean> childMenu = ListBuilder.newArrayList();
					childMenu.add(selectedMenu);
					selectedParentMenu.setChildren(childMenu);
					return selectedParentMenu;
				}
			}
		}
		return null;
	}
}